package com.morgan.recyclerviewdemo

import android.os.Bundle
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.morgan.recyclerviewdemo.utils.DeviceUtil
import kotlinx.android.synthetic.main.act_gesture_detector.*

class GestureDetectorAct : AppCompatActivity(){

    private val mGestureDetector : GestureDetector by lazy {
        GestureDetector(applicationContext
            , OnFlingGestureListener(DeviceUtil.dp2px(applicationContext, 50f), DeviceUtil.dp2px(applicationContext, 50f), {
                Log.e("morgan", "onFling hanpen")
            })) }


    private class OnFlingGestureListener(val minXDistence : Int, val minYDistence : Int,val onFling : () -> Unit) : GestureDetector.SimpleOnGestureListener() {
        override fun onFling(
            e1: MotionEvent?,
            e2: MotionEvent?,
            velocityX: Float,
            velocityY: Float
        ): Boolean {
            if (e1 == null || e2 == null) {
                return false
            }
             if (Math.abs(e1.x - e2.x) > minXDistence || Math.abs(e1.y - e2.y) > minYDistence) {
                 onFling.invoke()
                 return true
             }
            return false
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.act_gesture_detector)
        root.setOnTouchListener(object : View.OnTouchListener {
            override fun onTouch(v: View?, event: MotionEvent?): Boolean = mGestureDetector.onTouchEvent(event)
        })
        root.isClickable = true
    }
}